<template>
  <view class="viewport">
    <u-loading-page :loading="true" loading-text="努力登录中···"></u-loading-page>
  </view>
</template>

<script setup lang="ts">
import { postBuildAuthorizationUrlAPI, postLoginAPI } from '@/services/login'
import { useMemberStore } from '@/stores'
import { onLoad } from '@dcloudio/uni-app'
import { getMemberProfileAPI } from '@/services/profile'
import { active, clientId } from '@/config'
// 获取页面参数
const query = defineProps<{
  code: string
  state: string
}>()

onLoad(async () => {
  if (query.code) {
    await onLogin()
  } else {
    //生成授权连接
    let res = await postBuildAuthorizationUrlAPI({
      param: 'route',
      redirectUri: window.location.href,
      scope: 'snsapi_base',
      simple: active === 'dev',
      tenantId: '000000',
    })
    location.href = res.data.url
  }
})

const onLogin = async () => {
  const res = await postLoginAPI({
    clientId: clientId,
    grantType: 'wecom',
    simple: active === 'dev',
    tenantId: '000000',
    wecomCode: query.code,
  })
  loginSuccess(res.data)
}

const loginSuccess = async (profile: any) => {
  // 保存会员信息
  const memberStore = useMemberStore()
  memberStore.setProfile({
    token: profile.access_token,
    mobile: '',
    Clientid: profile.client_id,
    username: profile.client_id,
  })
  const res = await getMemberProfileAPI()
  profile.value = res.data
  // 同步 Store 的头像和昵称，用于我的页面展示
  memberStore.profile!.avatarUrl = res.data.user.avatar
  memberStore.profile!.nickName = res.data.user.nickName
  memberStore.profile!.username = res.data.user.userName
  memberStore.profile!.id = res.data.user.userId

  let url = uni.getStorageSync('loginBeforePage')
  console.log('url', url)
  if (
    url === '/pages/index/index' ||
    url === '/pages/customer/index' ||
    url === '/pages/tool/index' ||
    url === '/pages/corpus/index'
  ) {
    uni.switchTab({
      url: url,
    })
  } else {
    uni.redirectTo({
      url: url,
    })
  }
}
</script>

<style lang="scss"></style>
